layui.use(['laytpl', 'layer', 'layedit', 'form'], function () {
    var laytpl = layui.laytpl,
        layer = layui.layer,
        $ = layui.$,
        form = layui.form,
        layedit = layui.layedit;

    var wanted = false;
    var curGoods = {};
    var comments = {};
    var prefix = "../../upload/img/goods/";
    var headerPrefix = "../../upload/img/header/";
    var sellerName;
    var sellerId ;
    var sellerHeadImg;

    $(document).ready(function (){

        showCurGoods();

        addListener();
        initMagnifier();
        showComment();
    });

    function addListener() {
        $("#want-btn").click(function () {
            if (wanted) {
                console.log(wanted);
                $('#want-btn').css("background-color", "#FFF");
                $('#want-btn').css("color", "#1E9FFF");
            } else {
                $('#want-btn').css("background-color", "#1E9FFF");
                $('#want-btn').css("color", "#FFF");
            }
            wanted = !wanted;
        });

        //联系卖家
        $(document).on("click",'#contactBtn', function () {
            curSendTargetUser = sellerName;
            curSendTargetId[curSendTargetUser]= sellerId;
            chatIndex = layer.open({
                type:1
                ,title:"正在与"+curSendTargetUser+"聊天"
                ,content: $('#chatLayer').html()
                ,area:'auto'
                ,scrollbar:false
                ,maxWidth:900
                ,maxHeight:500
                ,success:function () {
                    console.log("打开聊天窗口");
                    isOpenedChatBox = true;
                    addChatList();
                    var c = tempMsg.hasOwnProperty(curSendTargetUser)?tempMsg[curSendTargetUser]:"";
                    $('#content').append(c);
                    // $(document).on('keydown',function(event){
                    //     if(event.keyCode === 13 && isOpenedChatBox===true){
                    //         var edit = $('#editText');
                    //         if (edit.val() === "") {
                    //             layer.msg("输入的内容不能为空");
                    //             return ;
                    //         }
                    //         var v = $('#content');
                    //
                    //         var c = getRenderSendMsg('../upload/img/header/header.png',edit.val());
                    //
                    //         var d = getRenderReceiveMsg('../upload/img/header/header.png',edit.val());
                    //         v.append(c);
                    //         v.append(d);
                    //         stompClient.send("/ws/message", {},
                    //             JSON.stringify({'fromId':21,'toId':22,'content':c}));
                    //         edit.val("");
                    //         document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight;
                    //     }
                    // });
                    $(document).on("click",'#send', function () {
                        var edit = $('#editText');
                        if (edit.val() === "") {
                            return ;
                        }
                        var v = $('#content');

                        var headerImg = $("#userHeadImg").attr('src');
                        var c = getRenderSendMsg(headerImg,edit.val());

                        v.append(c);
                        stompClient.send("/ws/message", {},
                                        JSON.stringify({'fromId':localStorage.getItem("userId"),'toId':curSendTargetId[curSendTargetUser],
                                            'fromName':localStorage.getItem('nickname'),'content':edit.val(),'headerImg':headerImg}));
                        edit.val("");
                        document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight;
                    });
                }
                ,cancel:function () {
                    isOpenedChatBox = false;
                    tempMsg[curSendTargetUser] = $('#content').html();
                    console.log(tempMsg[curSendTargetUser]);
                    clearMap(containChatItems);
                    console.log("关闭聊天窗口");
                }
            });
        });



        $(document).on('click',"#addComment",(function () {
            layer.open({
                title: "添加评论",
                type: 1,
                content: $('#addCommentForm').html(),
                area: '500px',
                maxHeight: '300px',
                success: function () {
                    layedit.set({
                        uploadImage: {
                            url: './image.json',
                            type: 'GET'
                        }
                    });
                    var index = layedit.build('commentContent', {
                        tool: ['left', 'center', 'right']
                    });
                    form.render();
                    $("#publishCommentBtn").click(function () {
                        console.log(layedit.getText(index) + "  userid" + localStorage.getItem("userId")
                            + "-----goodsId-->" + sessionStorage.getItem("curGoodsId"));

                        var data = new FormData();
                        data.append("userId", localStorage.getItem("userId"));
                        data.append("goodsId", sessionStorage.getItem("curGoodsId"));
                        data.append("content", layedit.getText(index));
                        data.append("timeCreate", new Date().Format("yyyy-MM-dd HH:mm:ss"));
                        $.ajax({
                            type: "POST"
                            , url: '/api/comment/new'
                            , contentType: false
                            , dataType: "json"
                            , cache: false
                            , processData: false
                            , data: data
                            , timeout: 6000
                            , success: function (ret) {
                                console.log(ret);
                                if (ret.code === 0) {
                                    layer.closeAll('loading');
                                    layer.msg("发表成功");
                                }

                                if (ret.code === 1|| ret.code === 3 ) {
                                    layer.msg(ret.msg);
                                    layer.msg("请登录");
                                }
                                if (ret.code === -1) {
                                    layer.msg(ret.msg);
                                    layer.msg("未知的错误~");
                                }
                                setTimeout(function () {
                                    layer.closeAll();
                                },1000);
                            }
                            , error: function () {
                                layer.msg('服务器正在休息~待会再来~');
                                setTimeout(function () {
                                    layer.closeAll('loading');
                                }, 1000);
                            }
                        });
                        return false;
                    });
                }
            })
            ;
        }));
    }

    function showCurGoods() {
        $.ajax({
            type:"GET"
            ,async:false
            ,url:"/api/goods/"+sessionStorage.getItem("curGoodsId")
            ,success:function (ret) {
                console.log(ret);

                if (ret.code === 0){
                    ret.data.src = prefix+ret.data.src;
                    ret.data.src = ret.data.src.substring(0,ret.data.src.length-1);
                    curGoods.count = 1;
                    curGoods.list = [];
                    curGoods.list[0] = ret.data;
                    console.log(curGoods);
                    sellerName = ret.data.sellerName;
                    sellerId = ret.data.sellerId;
                    sellerHeadImg = ret.data.sellerImg;
                    renderGoods();
                }

                if(ret.code === 3){
                    layer.msg("请登录");
                    logout();
                }
            }
            ,error:function (ret) {

            }
        })
    }

    function showComment() {
        $.ajax({
            type:"GET"
            ,async:false
            ,url:"/api/comment/list/"+sessionStorage.getItem("curGoodsId")
            ,timeout:6000
            ,success:function (ret) {
                console.log(ret);

                if (ret.code === 0){
                    comments.list = ret.data;
                    comments.count = ret.count;
                    for(var i = 0;i<ret.count;i++){
                        comments.list[i].headerImg = headerPrefix.toString()+ comments.list[i].headerImg;
                        //comments.list[i].headerImg =comments.list[i].headerImg.substring(0,comments.list[i].headerImg.length-1);

                    }
                    renderCommentList();
                }

                if(ret.code === 3){
                    layer.msg("请登录");
                }
            }
            ,error:function (ret) {

            }
        })
    }

    //渲染商品细节
    function renderGoods() {
        var getTpl = goodsDetailsTpl.innerHTML,
            view = document.getElementById('details');
        laytpl(getTpl).render(curGoods, function (html) {
            view.innerHTML = html;
        });
    }
    function renderCommentList() {
        var getTpl = commentListTpl.innerHTML,
            view = document.getElementById('commentList');
        laytpl(getTpl).render(comments, function (html) {
            view.innerHTML = html;
        });
    }

    function initMagnifier() {
        var evt = new Event(),
            m = new Magnifier(evt);
        m.attach({
            thumb: '#thumb',
            largeWrapper: 'preview'
        });
    }

    //添加当前聊天对象到聊天框左侧列表
    function addChatList() {
        var item = " <div id=\"chatItem\" class='"+sellerId+"' style=\"width: 145px;height: 30px;background: #01AAED;color: #00F7DE;font-size: 15px;padding:5px\">\n" +
            "                "+sellerName+"\n" +
            "            </div>";
        $('div#chatList').append(item);
        containChatItems[sellerName] = true;
    }

});